package cn.android.support.v7.lib.sin.crown.view;

import android.content.Context;
import android.graphics.Camera;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

import cn.android.support.v7.lib.sin.crown.R;
import cn.android.support.v7.lib.sin.crown.utils.ProportionUtils;
import cn.android.support.v7.lib.sin.crown.utils.ToastUtils;
//        使用说明
//        RollerView view = findViewById(R.id.myFramLayout);
//        final List<String> items = new ArrayList<>();
//        for (int i = 1; i <= 12; i++) {
//            items.add(i + "月");
//        }
//        view.setItems(items);//添加数据
//        view.setItemSelectListener(new RollerView.ItemSelectListener() {//添加回调
//            @Override
//            public void onItemSelect(String item, int postion) {
//                //Log.e("test", "数据:\t" + item + "\t下标:\t" + postion);
//            }
//        });
//        view.setCurrentPostion(6,true);//选中指定下标

//注意：android:layout_width="@dimen/x100_100" 設置寬度和高度時候，一定要設置明確的值。不能設置為0dp ,不然子View無法顯示。

/**
 * 滚轮选择器【新版】,华为mate9+荣耀8，不支持rotationx()旋转属性。会显示不见。
 * Created by 彭治铭 on 2018/3/29.
 */

public class RollerView2 extends RecyclerView {
    /**
     * 设置中间两条线条的颜色
     *
     * @param lineColor
     */
    public RollerView2 setLineColor(int lineColor) {
        this.lineColor = lineColor;
        return this;
    }

    /**
     * 设置线条的高度【边框的宽度】
     *
     * @param strokeWidth
     */
    public RollerView2 setStrokeWidth(int strokeWidth) {
        this.strokeWidth = strokeWidth;
        return this;
    }

    /**
     * 设置选中字体的颜色
     *
     * @param selectTextColor
     */
    public RollerView2 setSelectTextColor(int selectTextColor) {
        this.selectTextColor = selectTextColor;
        return this;
    }

    /**
     * 设置默认字体的颜色
     *
     * @param defaultTextColor
     */
    public RollerView2 setDefaultTextColor(int defaultTextColor) {
        this.defaultTextColor = defaultTextColor;
        return this;
    }

    /**
     * 设置回调接口，返回选中的数据和下标
     *
     * @param itemSelectListener
     */
    public RollerView2 setItemSelectListener(ItemSelectListener itemSelectListener) {
        this.itemSelectListener = itemSelectListener;
        return this;
    }

    /**
     * 設置當前顯示item的個數【一定要在設置數據之前，設置。必須】
     *
     * @param count
     */
    public RollerView2 setCount(int count) {
        this.count = count;
        pos = (count - 1) / 2;
        chidHeith = height / count;
        return this;
    }

    /**
     * fixme ======================================================================================= 设置数据集合
     *
     * @param items
     */
    public RollerView2 setItems(List<String> items) {
        if (this.items == null) {
            this.items = new ArrayList<>();//与参数传入的数据不会发生关联。
            linearLayoutManager = new LinearLayoutManager(getContext());
            linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            setLayoutManager(linearLayoutManager);
        }
        this.items.clear();
        this.items.addAll(items);
        for (int i = 0; i < pos; i++) {
            //补差值
            //向头部和末尾添加空数据。防止滑动无法滚动到第一个和最后一个。
            this.items.add(0, "");
            this.items.add("");
        }
        //每一次數據更新，最好適配器重新實例化。以及重置偏移量。不然偏移量不准。
        totalDy = 0;//归零。
        setAdapter(new MyAdapter());//适配器重新实例化，根本上解决数据和偏移量不准的问题。
        //getAdapter().notifyDataSetChanged();
        setCurrentPostion(currentPostion, true);
        return this;
    }

    /**
     * 选中指定下标【数据集合的实际下标】。
     *
     * @param position 下标【不算空格。是原数据的下标，即实际下标。】
     * @param isdelay  是否需要延长，首次调用最好延迟。
     */
    public RollerView2 setCurrentPostion(int position, boolean isdelay) {
        if (position >= items.size()) {
            currentPostion = pos;
        } else {
            currentPostion = position;
        }
        if (isdelay) {
            postDelayed(new Runnable() {
                @Override
                public void run() {
                    //scrollToPosition();没有效果
                    //smoothScrollBy()首次调用，最好延迟100毫秒左右。不然不灵。
                    smoothScrollBy(0, getDy(currentPostion));
                }
            }, 200);
        } else {
            smoothScrollBy(0, getDy(currentPostion));
        }
        return this;
    }

    //获取当前选中下标【不算空格。是原数据的下标，即实际下标。】
    public int getCurrentPostion() {
        return currentPostion;
    }

    //获取当前选中的值
    public String getCurrentItemValue() {
        return items.get(currentPostion + pos);
    }

    public RollerView2(Context context) {
        super(context);
        init();
    }

    public RollerView2(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    boolean smooth = false;
    private int totalDy = 0;//记录当前的滑动y的值。getScrollY()返回值总是0,所以y的值。只能自己手动记录。重新实例化适配器的时候，记得清零

    private void init() {
        setLayerType(View.LAYER_TYPE_HARDWARE, null);
        //滑动监听，只要实例化一次即可。不需要没有都添加。不然不准。
        //不要再生命周期函数中添加，避免重复添加滑动监听事件。添加一次即可。
        addOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                totalDy -= dy;
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (!smooth) {
                        int postion = linearLayoutManager.findFirstCompletelyVisibleItemPosition();
                        smooth = true;
                        currentPostion = postion;
                        if (itemSelectListener != null) {
                            itemSelectListener.onItemSelect(RollerView2.this.items.get(currentPostion + pos), currentPostion);//滑动回调
                        }
                        smoothScrollBy(0, totalDy + postion * chidHeith);//参数是偏移量，与当前位置的偏移量。不是具体的x,y左边。
                    }
                } else if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                    smooth = false;
                }
            }
        });

    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (paint == null) {
            paint = new Paint();
            paint.setAntiAlias(true);
            paint.setDither(true);
        }
        setLayerType(View.LAYER_TYPE_SOFTWARE, paint);
        setOverScrollMode(OVER_SCROLL_NEVER);//设置滑动到边缘时无效果模式
        setVerticalScrollBarEnabled(false);//滚动条隐藏
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
        chidHeith = height / count;
        startLine = chidHeith * pos;
        endLine = chidHeith * (pos + 1);
        centerY = height / 2;
        textSize = (float) ProportionUtils.getInstance().pixelToDp(chidHeith * 0.72);//字体大小。默认就是这个了。
    }

    Paint paint;
    int startLine;
    int endLine;
    int lineColor = Color.parseColor("#000000");//线条颜色
    int strokeWidth = (int) ProportionUtils.getInstance().getDimension(R.dimen.x2);//线条的宽度
    int offset = ProportionUtils.getInstance().adapterInt(3);//偏移量

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(lineColor);//线条颜色
        paint.setStrokeWidth(strokeWidth);//线条宽度
        //中间两条线
        canvas.drawLine(0, startLine, getWidth(), startLine, paint);
        canvas.drawLine(0, endLine, getWidth(), endLine, paint);
        paint.setColor(Color.BLACK);
        for (int i = 0; i < getChildCount(); i++) {
            ItemView view = (ItemView) getChildAt(i);
            view.setTextColor(defaultTextColor);
            float y = view.getY() + chidHeith / 2;
            if (view.getY() >= (startLine - offset) && view.getY() + chidHeith <= (endLine + offset)) {
                view.setTextColor(selectTextColor);//选中字体颜色
            } else {
                view.setTextColor(defaultTextColor);
            }
            if (y <= centerY) {
                //上面
                float dy = centerY - y;
                float degree = dy / (float) centerY * 90;
                if (degree > 90) {
                    degree = 90;
                }
                view.setRotationX(degree);
//                Log.e("test","下标:\t"+i+"\t角度:\t"+degree);
            } else if (y > centerY) {
                //下面
                float dy = y - centerY;
                float degree = dy / (float) centerY * 90;
                if (degree > 90) {
                    degree = 90;
                }
                view.setRotationX(-degree);
//                Log.e("test","下标2:\t"+i+"\t角度:\t"+(-degree));
            }
        }
    }

    int width;
    int height;
    int count = 5;//显示的个数(奇数，上下要对齐偶数是不行的)
    int chidHeith;//子View的高度
    float textSize;//文本大小
    int selectTextColor = Color.parseColor("#444444");
    int defaultTextColor = Color.parseColor("#888888");
    int pos = (count - 1) / 2;//中间下标与当前显示的第一个item的下标之差。
    public int currentPostion = pos;//默认选中下标。（中间的那个item）
    int centerY;//中间Y坐标。
    List<String> items;//数据集合
    LinearLayoutManager linearLayoutManager;
    ItemSelectListener itemSelectListener;//回调函数，返回下标和对应的数据

    //获得滑动偏移量
    public int getDy(int currentPostion) {
        this.currentPostion = currentPostion;
        int postion = linearLayoutManager.findFirstCompletelyVisibleItemPosition();
        int y = postion * chidHeith;
        int y2 = (currentPostion) * chidHeith;
        int dy = y2 - y;
        return dy;
    }

    //回调
    public interface ItemSelectListener {
        //原始数据，和下标
        void onItemSelect(String item, int position);
    }

    //子View
    class ItemView extends android.support.v7.widget.AppCompatTextView {

        public ItemView(Context context) {
            super(context);
            setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }

        @Override
        protected void onAttachedToWindow() {
            super.onAttachedToWindow();
            //setLayerType(View.LAYER_TYPE_HARDWARE, paint);//子View不要开，父类开即可。不然对父类绘图有不好的影响。
            setGravity(Gravity.CENTER);
        }

        @Override
        protected void onSizeChanged(int w, int h, int oldw, int oldh) {
            super.onSizeChanged(w, h, oldw, oldh);
            this.setPivotX(w / 2);
            this.setPivotY(h / 2);
        }

    }

    class MyViewHolder extends ViewHolder {
        ItemView itemView;

        public MyViewHolder(ItemView itemView) {
            super(itemView);
            this.itemView = itemView;
            this.itemView.setLayoutParams(new ViewGroup.LayoutParams(width, chidHeith));
            this.itemView.setTextSize(textSize);//字体大小
            this.itemView.setGravity(Gravity.CENTER);//居中
            //ToastUtils.showToastView("寬度:\t"+width+"\t高度:\t"+chidHeith+"\t個數:\t"+count+"\t字體大小:\t"+textSize);
        }

    }

    class MyAdapter extends Adapter<MyViewHolder> {

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new MyViewHolder(new ItemView(getContext()));
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, final int position) {
            //ToastUtils.showToastView("总个数：\t"+getItemCount()+"下标:\t"+position+"\titems:\t"+items);
            if (items.get(position) != null && !items.get(position).trim().equals("")) {
                //Log.e("test","总个数:\t"+getItemCount()+"\t下标:\t"+position+"\t文本:\t"+items.get(position));
                holder.itemView.setText(items.get(position));
                holder.itemView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        currentPostion = position - pos;
                        if (itemSelectListener != null) {
                            itemSelectListener.onItemSelect(items.get(currentPostion + pos), currentPostion);//点击回调
                        }
                        setCurrentPostion(currentPostion, false);
                    }
                });
            }
        }

        @Override
        public int getItemCount() {
            int count = items != null ? items.size() : 0;
            return count;
        }

        @Override
        public int getItemViewType(int position) {
            return position;
        }
    }

}
